package com.bluesky.jwf.component.list;

import java.util.ArrayList;
import java.util.List;

import com.bluesky.javawebbrowser.domain.html.tags.Tag;
import com.bluesky.jwf.ComponentFactory;
import com.bluesky.jwf.component.Component;
import com.bluesky.jwf.component.event.EventHandler;

/**
 * it is a general list, the list item can be anything.
 * 
 * @author jack
 * 
 */
public class ListView extends Component {
	public static String EVENT_REFRESH = "refresh";

	private String title;
	/*
	 * the model.
	 */
	protected Object model;

	protected Tag titleTag;
	protected Tag listTag;
	protected Tag itemTag;

	protected Class itemClass;

	protected List<ListItem> listItems;

	public ListView() {
		listItems = new ArrayList<ListItem>();
	}

	@Override
	public void init(String html) {

		super.init(html);

		titleTag = getByJwfClass("title");// optional
		listTag = loadByJwfClass("list");
		itemTag = listTag.loadByJwfClass("item");

		listTag.removeChild(itemTag);

	}

	public void dataBind() {

		listItems.clear();
		int i = 0;
		for (Object o : (List) model) {
			ListItem listItem = (ListItem) ComponentFactory.getInstance()
					.createComponent(itemClass.getName(), itemTag.toHtml());

			listItem.setListView(this);
			listItem.setIndex(i);
			listItem.setModel(o);

			listItems.add(listItem);

			i++;
		}

		updateView();
	}

	/**
	 * update the view of expanded/collapsed.
	 */
	protected void updateView() {
		listTag.removeAllChildren();

		for (ListItem li : listItems) {
			li.updateView();

			listTag.addChild(li);
		}
	}

	public Object getModel() {
		return model;
	}

	public void setModel(Object model) {
		this.model = model;
	}

	public void refresh() {
		handleEvent(EVENT_REFRESH);
	}

	public void setRefreshHandler(EventHandler handler) {
		eventHandlers.put(EVENT_REFRESH, handler);
	}

	public void setTitle(String title) {
		this.title = title;

		if (this.titleTag != null)
			this.titleTag.setBodyAndParse(title);
	}

	public Class getItemClass() {
		return itemClass;
	}

	public void setItemClass(Class itemClass) {
		this.itemClass = itemClass;
	}

	public String getTitle() {
		return title;
	}

	public List<ListItem> getListItems() {
		return listItems;
	}

	public void setListItems(List<ListItem> listItems) {
		this.listItems = listItems;
	}

}
